package com.flycat.interceptor;

import com.alibaba.fastjson.JSON;
import com.flycat.common.util.SessionUtils;
import com.flycat.core.Result;
import com.flycat.dao.po.MerchantInfo;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 认证拦截器，用于用户是否登陆的判断
 * @Author yalei.chen
 * @Date 2017/10/17
 * @Since JDK 1.8
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private ApplicationContext context;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        MerchantInfo user = (MerchantInfo) session.getAttribute(SessionUtils.STORE_SESSION_USER);
        if (user != null) {
            return true;
        }

        String servletPath = request.getServletPath();
        String queryString = request.getQueryString();

        SessionUtils.setSession(request,SessionUtils.STORE_SESSION_PREURL,servletPath+(null == queryString?"":"?"+queryString));
        //跳转至登录页面
        response.sendRedirect(request.getContextPath()+"/login");
        return false;
    }



    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
